<?php
header('Content-Type: application/json; charset=utf-8');

// 读取POST数据
$uploader_id = $_POST['上传者用户的id'] ?? '';
$file_title = $_POST['文件标题'] ?? '';
$file_description = $_POST['文件介绍'] ?? '';
$file_size = $_POST['文件大小'] ?? '';
$file_format = $_POST['文件格式'] ?? '';
$likes = $_POST['获赞数量'] ?? '';
$file_link = $_POST['文件链接'] ?? '';
$file_cover = $_POST['文件封面'] ?? '';
$file_icon = $_POST['文件图标'] ?? '';
$notes = $_POST['文件备注'] ?? '';
$upload_time = $_POST['上传时间'] ?? date('Y-m-d H:i:s'); // 默认当前时间
$audited = $_POST['是否已审核'] ?? '';
$auditor_id = $_POST['审核者的用户id'] ?? '';
$rejection_reason = $_POST['拒绝原因'] ?? '';

// 连接数据库
try {
    $dbConfig = include('db_config.php');
    $dsn = "mysql:host=" . $dbConfig['host'] . ";dbname=" . $dbConfig['dbname'] . ";charset=" . $dbConfig['charset'];
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 插入数据的SQL语句
    $insertFileSQL = "
        INSERT INTO mi_file (
            上传者用户的id,
            文件标题,
            文件介绍,
            文件大小,
            文件格式,
            获赞数量,
            文件链接,
            文件封面,
            文件图标,
            文件备注,
            上传时间,
            是否已审核,
            审核者的用户id,
            拒绝原因
        ) VALUES (
            :uploader_id,
            :file_title,
            :file_description,
            :file_size,
            :file_format,
            :likes,
            :file_link,
            :file_cover,
            :file_icon,
            :notes,
            :upload_time,
            :audited,
            :auditor_id,
            :rejection_reason
        )
    ";

    // 使用预处理语句插入数据
    $stmt = $pdo->prepare($insertFileSQL);
    $stmt->bindParam(':uploader_id', $uploader_id);
    $stmt->bindParam(':file_title', $file_title);
    $stmt->bindParam(':file_description', $file_description);
    $stmt->bindParam(':file_size', $file_size);
    $stmt->bindParam(':file_format', $file_format);
    $stmt->bindParam(':likes', $likes);
    $stmt->bindParam(':file_link', $file_link);
    $stmt->bindParam(':file_cover', $file_cover);
    $stmt->bindParam(':file_icon', $file_icon);
    $stmt->bindParam(':notes', $notes);
    $stmt->bindParam(':upload_time', $upload_time);
    $stmt->bindParam(':audited', $audited);
    $stmt->bindParam(':auditor_id', $auditor_id);
    $stmt->bindParam(':rejection_reason', $rejection_reason);

    $stmt->execute();

    // 返回成功结果
    echo json_encode(['status' => 'success', 'message' => '文件添加成功'], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
    // 捕获异常并返回错误信息
    $errorResult = [
        'status' => 'error',
        'message' => '数据库操作失败：' . $e->getMessage()
    ];
    echo json_encode($errorResult, JSON_UNESCAPED_UNICODE);
}
